package com.gxc.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.gxc.dto.User;
import com.gxc.exception.UserNotExistException;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author GongXincheng
 * @since 2019-10-12 15:38
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/me")
    public Object getCurrentUser() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 方式2.
     */
    @GetMapping("/me2")
    public Object getCurrentUser2(Authentication authentication) {
        return authentication;
    }

    @GetMapping("/me3")
    public Object getCurrentUser3(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }

    @GetMapping
    @JsonView(User.UserSimpleView.class)
    public List<User> query(User param, @PageableDefault(page = 1, size = 12, sort = "username", direction = Sort.Direction.DESC) Pageable pageable) {
        System.out.println(param);
        System.out.println(pageable.getPageNumber());
        System.out.println(pageable.getPageSize());
        System.out.println(pageable.getSort());

        List<User> list = new ArrayList<>(3);
        for (int i = 0; i < 3; i++) {
            User user = new User("name" + i, "pwd" + i, i, new Date());
            list.add(user);
        }
        return list;
    }

    @GetMapping("/{id:\\d+}")
    @JsonView(User.UserDetailView.class)
    public User getInfo(@PathVariable Integer id) {
        if (Objects.equals(id, 0)) {
            throw new UserNotExistException(id);
        }

        System.out.println(id);
        return new User("gxc", "", 1, new Date());
    }


    @PostMapping
    public User create(@RequestBody @Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            bindingResult.getAllErrors().forEach(e -> System.out.println(e.getDefaultMessage()));
        }
        System.out.println(user);
        user.setId(1);
        return user;
    }


}
